import * as XLSX from "xlsx";
import { addData, deleteDBAll, openDB, getDataByKey } from "./indexdb";
export async function uploadFile() {
  // deleteDBAll("list").then((res) => {});
  // // deleteDBAll("list").then(() => {
  // //   openDB("car", "list");
  // // });
  openDB("car", "list");
  if ("showOpenFilePicker" in window) {
    const handle = await window.showDirectoryPicker();
    const ent = await handle.entries();
    deleteDBAll();
    for await (const item of ent) {
      item[1].getFile().then((res) => {
        toJson(res);
      });
    }

    // const fileListElement = doc
  } else {
    alert("不支持");
  }
}

function toJson(file) {
  const reader = new FileReader();
  reader.readAsArrayBuffer(file);
  reader.onload = function (e) {
    // excel文件 —— array
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    // 假设我们只读取第一个工作表
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    const file_name = file.name.split(".")[0];
    addData("list", { id: file_name, data: jsonData });
  };
}

export async function exportData(datas, name) {
  const stringifiedData = datas.map((obj) => {
    const stringifiedObj = {};
    for (const key in obj) {
      stringifiedObj[key] = String(obj[key]);
    }
    return stringifiedObj;
  });
  // 自定义数据
  const data = stringifiedData || [];
  // 将自定义数据转换为工作表
  const worksheet = XLSX.utils.json_to_sheet(data);
  // 创建一个新的工作簿
  const workbook = XLSX.utils.book_new();
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, name);
  // 导出为 Excel 文件
  XLSX.writeFile(workbook, `${name}.xlsx`);
}
